const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)

const host = 'ws://172.16.11.52:8083/mqtt'

const options = {
  keepalive: 60,
  clientId: clientId,
  username: 'mica',
  password: 'mica',
  protocolId: 'MQTT',
  protocolVersion: 4,
  clean: true,
  reconnectPeriod: 1000,
  connectTimeout: 30 * 1000,
  will: {
    topic: 'WillMsg',
    payload: 'Connection Closed abnormally..!',
    qos: 0,
    retain: false
  },
}

console.log('Connecting mqtt client')
const client = mqtt.connect(host, options)

client.on('error', (err) => {
  console.log('Connection error: ', err)
  client.end()
})

client.on('reconnect', () => {
  console.log('Reconnecting...')
})

// 成功连接后触发的回调
client.on('connect', () => {
  console.log('已经连接成功');
  // 订阅主题，这里可以订阅多个主题
  client.subscribe(["/mqtt1/device/1"], () => {
    console.log(`订阅了主题`)
  })
});

